package bistu.grobot.oor;
//
//import android.support.v7.app.AppCompatActivity;
//import android.os.Bundle;
//import android.widget.TextView;
//
//public class MainActivity extends AppCompatActivity {
//
//    // Used to load the 'native-lib' library on application startup.
//    static {
//        System.loadLibrary("native-lib");
//    }
//
//    @Override
//    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//
//        // Example of a call to a native method
//        TextView tv = (TextView) findViewById(R.id.sample_text);
//        tv.setText(stringFromJNI());
//    }
//
//    /**
//     * A native method that is implemented by the 'native-lib' native library,
//     * which is packaged with this application.
//     */
//    public native String stringFromJNI();
//}
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.nio.ByteBuffer;

import static android.content.ContentValues.TAG;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private static int RESULT_LOAD_IMAGE1 = 1;
    //private static int RESULT_LOAD_IMAGE2 = 2;
    private TextView infoResult;
    private ImageView image1 = null;
    //private ImageView image2 = null;

    private Button selectBtn1 = null;
    //private Button selectBtn2 = null;
    private Button compareBtn = null;

    private TextView resultInfo = null;
    private Bitmap bitmap1 = null;


    //private Bitmap bitmap2 = null;
    private String[] class_name = { "background",
            "海参", "海胆", "扇贝", "海星",
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
        selectBtn1.setOnClickListener(this);
        //selectBtn2.setOnClickListener(this);
        compareBtn.setOnClickListener(this);
    }
    //获取需要控件
    public void init() {
        image1 = (ImageView) findViewById(R.id.image1);
        //image2 = (ImageView) findViewById(R.id.image2);

        selectBtn1 = (Button) findViewById(R.id.selectBtn1);
        //selectBtn2 = (Button) findViewById(R.id.selectBtn2);
        compareBtn = (Button) findViewById(R.id.compareBtn);

        resultInfo = (TextView) findViewById(R.id.infoResult);
    }

    //点击事件
    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.selectBtn1) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE},RESULT_LOAD_IMAGE1);
            } else {
                readImages(RESULT_LOAD_IMAGE1);
            }
        }
//        else if (view.getId() == R.id.selectBtn2) {
//            if (ContextCompat.checkSelfPermission(this,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                    != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(MainActivity.this,new String[]{
//                        Manifest.permission.WRITE_EXTERNAL_STORAGE},RESULT_LOAD_IMAGE1);
//            } else {
//                readImages(RESULT_LOAD_IMAGE2);
//            }
//        }
        else if (view.getId() == R.id.compareBtn) {
            long timeDetect = System.currentTimeMillis();
            int faceInfo[] = null;
            String resultStr = detectImage(bitmap1); //对比图片
            timeDetect = System.currentTimeMillis() - timeDetect;
            Log.i(TAG, "平均检测时间："+timeDetect);
            resultInfo.setVisibility(View.VISIBLE);
            //resultInfo.setText(resultStr); //显示结果
        }
        else if(view.getId() == R.id.infoResult){
            infoResult.setMovementMethod(ScrollingMovementMethod.getInstance());
        }

    }


    //读取本地图库
    public void readImages(int icode) {
        Intent select = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(select, icode);
    }

    //加载图片
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();

            if (requestCode == RESULT_LOAD_IMAGE1 ) {
                bitmap1 = BitmapFactory.decodeFile(picturePath);
                image1.setImageBitmap(bitmap1);
            }
//            else if (requestCode == RESULT_LOAD_IMAGE2) {
//                bitmap2 = BitmapFactory.decodeFile(picturePath);
//                image2.setImageBitmap(bitmap2);
//            }
        }

    }

    //权限申请处理
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {

        if (requestCode == RESULT_LOAD_IMAGE1)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                readImages(requestCode);
            } else {
                Toast.makeText(MainActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
        }
    }
    //提取像素点
    private byte[] getPixelsRGBA(Bitmap image) {
        // calculate how many bytes our image consists of
        int bytes = image.getByteCount();
        ByteBuffer buffer = ByteBuffer.allocate(bytes); // Create a new buffer
        image.copyPixelsToBuffer(buffer); // Move the byte data to the buffer
        byte[] temp = buffer.array(); // Get the underlying array containing the

        return temp;
    }

    //图片对比
    public String detectImage(Bitmap bitmap1) {
        //模型初始化
        File sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        String sdPath = sdDir.toString() + "/coor/";
//        Log.i(TAG, "end copy file " + sdPath);
        CoorModelInit(sdPath);

        SetNumThreads(4);

        int width1 = bitmap1.getWidth();
        int height1 = bitmap1.getHeight();
        byte[] imageDate1 = getPixelsRGBA(bitmap1);

        float objects[] = null;

        //vyreg.FaceExtractCodeModelUnInit();
        objects = CoorDetect(imageDate1, width1, height1, 4);
        Log.i(TAG, "facecode1 0 " + Float.toString(objects[0]));
        Bitmap drawBitmap = bitmap1.copy(Bitmap.Config.ARGB_8888, true);
        int objNum = (int) (objects[0]);
        if (objNum > 0) {
            resultInfo.setVisibility(View.VISIBLE);
            infoResult = (TextView) findViewById(R.id.infoResult);
            String disp_info = String.format("检测到"+Integer.toString(objNum)+"个目标\n");
            //infoResult.setText("检测到"+Integer.toString(objNum)+"个目标\n");
            for (int i = 0; i < objNum; i++) {
                int left, top, right, bottom, label;
                float prob;
                Canvas canvas = new Canvas(drawBitmap);
                Paint paint = new Paint();
                Paint pen = new Paint();
                label = Math.round(objects[1 + 6 * i]);
                prob = objects[2 + 6 * i];
                left = Math.round(objects[3 + 6 * i]);
                top = Math.round(objects[4 + 6 * i]);
                right = Math.round(objects[5 + 6 * i]) + left - 1;
                bottom = Math.round(objects[6 + 6 * i]) + top - 1;
                disp_info = disp_info +String.format(Integer.toString(i)+":"+class_name[label]+" x="+Integer.toString(left)+"y="+Integer.toString(top)+"w="+Integer.toString(right-left+1)+"h="+Integer.toString(bottom-top+1)+"\n");
                switch (label)
                {
                    case 1:
                        paint.setColor(Color.RED);
                        break;
                    case 2:
                        paint.setColor(Color.GREEN);
                        break;
                    case 3:
                        paint.setColor(Color.BLUE);
                        break;
                    case 4:
                        paint.setColor(Color.YELLOW);
                        break;
                        default:
                            paint.setColor(Color.YELLOW);
                            break;

                }

                paint.setStyle(Paint.Style.STROKE);//不填充
                paint.setStrokeWidth(5);  //线的宽度
                canvas.drawRect(left, top, right, bottom, paint);
                pen.setColor(Color.WHITE);
                pen.setStyle(Paint.Style.STROKE);
                pen.setStrokeWidth(1);
                canvas.drawText(class_name[label], objects[3 + 6 * i], objects[4 + 6 * i], pen);
//            //画特征点
//            canvas.drawPoints(new float[]{faceInfo[5+14*i],faceInfo[10+14*i],
//                    faceInfo[6+14*i],faceInfo[11+14*i],
//                    faceInfo[7+14*i],faceInfo[12+14*i],
//                    faceInfo[8+14*i],faceInfo[13+14*i],
//                    faceInfo[9+14*i],faceInfo[14+14*i]}, paint);//画多个点
            }
            infoResult.setText(disp_info);
            infoResult.setGravity(View.TEXT_ALIGNMENT_CENTER);
            image1.setImageBitmap(drawBitmap);
        } else {
            infoResult = (TextView) findViewById(R.id.infoResult);
            infoResult.setText("未检测到人脸");
        }


        //LOGD("比分  %f\n",score);
        return Float.toString(objects[0]);


//        return null;
    }

    public native boolean CoorModelInit(String faceDetectionModelPath);
    public native float[] CoorDetect(byte[] imageDate, int imageWidth , int imageHeight, int imageChannel);
    public native boolean CoorModelUnInit();
    public native boolean SetInputSize(int resSize);
    public native int GetInputImgSize();
    public native boolean SetNumThreads(int numTreads);
    public native boolean SetTimeCount(int timeCount);
    static {
        System.loadLibrary("native-lib");
    }

}
